package stdio.costa.imoca.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import stdio.costa.imoca.dao.MocaUserDao;
import stdio.costa.imoca.model.MocaUser;


@Path("/user")
@Component
@Scope("request")
public class IMocaUserApi {

	@Autowired
	private MocaUserDao userDao;

	@Path("/login")
	@POST
	@Produces({ "application/json", "application/xml" })
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public MocaUser login(@FormParam("username") String username,
			@FormParam("password") String password) {

		MocaUser user = this.userDao.findUserByName(username);

		if (user == null || !isPasswordMatch(password, user)) {
			return null;
		}
		
		return user;
	}

	protected boolean isPasswordMatch(String password, MocaUser user) {
		return StringUtils.equals(DigestUtils.md5Hex(password),
				user.getPassword());
	}
	
	public static void main(String []args){
		System.out.println(DigestUtils.md5Hex("chao.qi"));
	}
}
